package com.kuqi.crs.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author:kuqi
 * @createTime:2021/9/23 10:36
 * @description:SqlSession对象的获取，与资源的关闭
 */
public class SqlSessionUtil {
    private static SqlSessionFactory sqlSessionFactory;

    //用于创建一个工厂，且只有一个SqlSession工厂
    static {
        String resource = "mybatis_config.xml";
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    }

    //创建一个线程池,多线程使用SqlSession对象
    private static ThreadLocal<SqlSession> t = new ThreadLocal<SqlSession>();

    //获取SqlSession对象
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = t.get();
        if (sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            t.set(sqlSession);
        }
        return sqlSession;
    }

    //关闭sqlSession对象资源，剥离线程与数据库的联系
    public static void myClose(SqlSession sqlSession){
        if (sqlSession != null){
            sqlSession.close();
            t.remove();
        }
    }
}
